package com.corner.ui.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.corner.R;
import com.corner.app.App;
import com.corner.app.ConsTants;
import com.corner.presenter.imp.GetSmsCodePresenter;
import com.corner.ui.activity.LoginAndRegisterActivity;
import com.corner.ui.base.BaseActivity;
import com.corner.ui.base.BaseFragment;
import com.corner.ui.listener.TextChangeListener;
import com.corner.ui.view.IGetSmsCodeView;
import com.corner.utils.SoftInputUtil;
import com.corner.utils.ToastUtil;
import com.corner.utils.view.CustomFont;
import com.corner.utils.view.FindView;

import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 获取验证码页面
 *
 * @author Administrator
 */
public class GetSmsCodeFragment extends BaseFragment<GetSmsCodePresenter> implements OnClickListener, IGetSmsCodeView {
    @CustomFont(ConsTants.TYPE_FACE)
    @FindView(R.id.btn_register_login_actionbar_back)
    private Button btnBack;

    @CustomFont(ConsTants.TYPE_FACE)
    @FindView(R.id.tv_get_sms_notice_1)
    private TextView tvNotice1;

    @CustomFont(ConsTants.TYPE_FACE)
    @FindView(R.id.tv_get_sms_notice_2)
    private TextView tvNotice2;

    @CustomFont(ConsTants.TYPE_FACE)
    @FindView(R.id.tv_get_sms_notice_3)
    private TextView tvNotice3;

    @CustomFont(ConsTants.TYPE_FACE)
    @FindView(R.id.et_phone_number_zone)
    private EditText etTimeZone;

    @CustomFont(ConsTants.TYPE_FACE)
    @FindView(R.id.et_phone_number_input)
    private EditText etPhoneInput;

    @CustomFont(ConsTants.TYPE_FACE)
    @FindView(R.id.et_sms_code_input)
    private EditText etCodeInput;

    @CustomFont(ConsTants.TYPE_FACE)
    @FindView(R.id.tv_get_sms_code)
    private TextView tvGetCode;

    @CustomFont(ConsTants.TYPE_FACE)
    @FindView(R.id.tv_sms_code_finish)
    private TextView tvFinish;

    /**
     * 是否wacher是可用状态，倒计时时是不可用状态
     */
    private boolean isPhoneWatcherOk = true;
    private int timeRemain;
    private String phoneNumber;

    @Override
    protected GetSmsCodePresenter createP() {
        return new GetSmsCodePresenter();
    }

    @Override
    protected void setOnclick() {
        btnBack.setOnClickListener(this);
        tvGetCode.setOnClickListener(this);
        tvFinish.setOnClickListener(this);
        etCodeInput.addTextChangedListener(new TextChangeListener() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                changeStateOfTvFinish(s);
            }
        });
        etPhoneInput.addTextChangedListener(new TextChangeListener() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                changeStateOfTvGetCode(s);
            }

        });

    }


    @Override
    protected View initView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.frag_get_sms_code, null);
        return view;
    }

    @Override
    public void onClick(View v) {
        SoftInputUtil.hideSoftInput(activity, view);

        switch (v.getId()) {

            case R.id.btn_register_login_actionbar_back:
                activity.popBackStack(LoginFragment.class
                        .getSimpleName());
                activity.changeFragment(
                        ((LoginAndRegisterActivity) activity).getLoginFragment(),
                        this, false);
                break;
            case R.id.tv_get_sms_code:
                getCodeEngine();
                break;
            case R.id.tv_sms_code_finish:
                vertifySmsCode();
                break;
        }
    }

    /**
     * 验证SMSCode
     */
    private void vertifySmsCode() {
        if (TextUtils.isEmpty(phoneNumber)) {
            return;
        }
        activity.excuteTaskWhenNetOk(new BaseActivity.Task() {
            @Override
            public void onExcute() {
                final String smsCode = etCodeInput.getText().toString();
                presenter.vertify(phoneNumber, smsCode);
            }
        });
    }

    /**
     * 点击后触发获取验证码的逻辑
     */
    private void getCodeEngine() {
        // 如果校验合格
        // 查询是否该用户已经注册，如果注册
        activity.excuteTaskWhenNetOk(new BaseActivity.Task() {
            @Override
            public void onExcute() {
                phoneNumber = etPhoneInput.getText().toString();
                presenter.getSmsCode(phoneNumber);
            }
        });
    }


    /**
     * 倒计时
     */
    private void timeDown() {
        // 设置TextWacher不可用
        isPhoneWatcherOk = false;
        tvGetCode.setEnabled(false);
        timeRemain = 60;
        Observable.timer(1, TimeUnit.SECONDS, Schedulers.immediate()).subscribeOn(Schedulers.io()).repeat(60)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Long>() {
            @Override
            public void call(Long aLong) {
                tvGetCode.setText(StringUtils.replace(
                        "验证码已发送，TIMEREMAIN秒后可再次收取", "TIMEREMAIN",
                        timeRemain-- + ""));
                if (timeRemain == 0) {
                    isPhoneWatcherOk = true;
                    changeStateOfTvGetCode(etPhoneInput.getText());
                    tvGetCode.setText(R.string.frag_get_sms_get_code);
                }
            }
        });
    }

    /**
     * 更改tvGetCode 的状态
     *
     * @param s
     */
    private void changeStateOfTvGetCode(CharSequence s) {
        if (isPhoneWatcherOk) {
            if (checkPhone(s)) {
                tvGetCode.setEnabled(true);
            } else {
                tvGetCode.setEnabled(false);
            }
        }
    }

    /**
     * 改变tvFinish的状态
     *
     * @param s
     */
    protected void changeStateOfTvFinish(CharSequence s) {
        if (s.length() == 6) {
            tvFinish.setEnabled(true);
        } else {
            tvFinish.setEnabled(false);
        }
    }

    /**
     * 校验电话
     *
     * @param s
     * @return
     */
    private boolean checkPhone(CharSequence s) {
        String regex = "1[358][0-9]{9}";
        return s.toString().matches(regex);
    }


    @Override
    public void vertifyError(String message) {
        ToastUtil.showCustomToastInRelease(App.application, message);
        activity.hideProgressDialog();
    }

    @Override
    public void getSmsSucess() {
        ToastUtil.showCustomToastInDevelop(App.application,
                R.string.sms_code_send_sucess);
        // 成功发送，验证码，倒计时1分钟
        timeDown();
    }

    @Override
    public void getSmsCodeError(String message) {
        ToastUtil.showCustomToastInRelease(App.application, message);
        // 发送失败
        isPhoneWatcherOk = true;
    }

    @Override
    public void loginSucess() {
        ToastUtil.showCustomToastInRelease(App.application, "您已经注册过，直接登录");
        ((LoginAndRegisterActivity) activity).goHome();
    }

    @Override
    public void phoneNumHasNotRegistered() {
        Bundle bundle = new Bundle();
        bundle.putString(SetPasswordFragment.PHONE_NUM, phoneNumber);
        ((LoginAndRegisterActivity) activity).getSetPasswordFragment().setArguments(bundle);
        activity.changeFragment(
                ((LoginAndRegisterActivity) activity).getSetPasswordFragment(),
                this, false);
    }
}
